//
//  TableViewCellComponent.swift
//  BaseViewControllerKit
//
//  Created by TSYH on 2024/5/14.
//

import Foundation

public protocol TableComponentView {
    // UI 渲染
    func renderView(with object: Any?, component: TableViewComponent, attributes: [String: Any]?)
}

public protocol TableViewSectionComponent: Component {
    var cellComponents: [TableViewCellComponent] { get }
    var headerComponent: TableViewReuseViewComponent? { get }
    var footerComponent: TableViewReuseViewComponent? { get }
    
    func append(children: Component)
}

public extension TableViewSectionComponent {
    var headerComponent: TableViewReuseViewComponent? { return nil }
    var footerComponent: TableViewReuseViewComponent? { return nil }
}

public enum TableViewReuseViewType {
    case header
    case footer
}

public protocol TableViewReuseViewComponent: Component {
    var viewType: TableViewReuseViewType { get }
    var viewClass: UITableViewHeaderFooterView.Type { get }
    var viewHeight: CGFloat { get }
}

public protocol TableViewRowAction {
    var image: UIImage? { get }
    var title: String? { get }
    var backgroundColor: UIColor? { get }
}

public protocol TableViewCellComponent: Component {
    var tableCellClass: UITableViewCell.Type { get }
    func cellHeight(with attrubites: [String: Any]?) -> CGFloat
    var editActions: [TableViewRowAction]? { get }
}

public extension TableViewCellComponent {
    var editActions: [TableViewRowAction]? { return nil }
}

public class DefaultTableViewSectionComponent: TableViewSectionComponent {
    var cells: [TableViewCellComponent]
    var header: TableViewReuseViewComponent?
    var footer: TableViewReuseViewComponent?
    
    init(cells: [TableViewCellComponent],
         header: TableViewReuseViewComponent? = nil,
         footer: TableViewReuseViewComponent? = nil) {
        self.cells = cells
        self.header = header
        self.footer = footer
    }
    
    public var cellComponents: [TableViewCellComponent] {
        return cells
    }
    
    public var headerComponent: TableViewReuseViewComponent? {
        return header
    }
    
    public var footerComponent: TableViewReuseViewComponent? {
        return footer
    }
    
    // 添加元素
    public func append(children: Component) {
        if let cell = children as? TableViewCellComponent {
            cells.append(cell)
        } else if let reuse = children as? TableViewReuseViewComponent {
            switch reuse.viewType {
            case .header:
                header = reuse
            case .footer:
                footer = reuse
            }
        }
    }
}
